//
//  PPMessageTimelineViewController.m
//  pickpic
//
//  Created by Jinxiao on 10/6/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPMessageTimelineViewController.h"
#import "PPProfileViewController.h"
#import "PPTimelinePictureViewController.h"
#import "PPTimelineDetailViewController.h"

#import "PPMessageTimelineTableViewCommentCell.h"
#import "PPMessageTimelineTableViewLikeCell.h"
#import "PPMessageTimelineTableViewFavoriteCell.h"

#import "PPUnreadMessageManager.h"

static const NSInteger kCount = 30;

@interface PPMessageTimelineViewController ()

@end

@implementation PPMessageTimelineViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"消息";

    [self.tableView registerClass:[PPMessageTimelineTableViewCommentCell class] forCellReuseIdentifier:@"commentCell"];
    [self.tableView registerClass:[PPMessageTimelineTableViewLikeCell class] forCellReuseIdentifier:@"likeCell"];
    [self.tableView registerClass:[PPMessageTimelineTableViewFavoriteCell class] forCellReuseIdentifier:@"favoriteCell"];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    __weak typeof(self)weakSelf = self;
    [self setNavigationRightTitle:@"清空" titleColor:[UIColor colorWithRGBHex:0xffdd17] action:^{
        [weakSelf clearItemDidPressed];
    }];

    [self updateNavigationBar];
}

- (void)updateNavigationBar {
    UIBarButtonItem *clearItem = self.navigationItem.rightBarButtonItem;

    clearItem.enabled = self.items.count > 0;
}

- (void)clearItemDidPressed {
    __weak typeof(self)weakSelf = self;

    DGBlockActionSheet *actionSheet = [DGBlockActionSheet actionSheetWithTitle:nil];
    [actionSheet addDestructiveButtonWithTitle:@"清空" clickBlock:^{
        [MobClick event:@"91"];
        [self removeAllItems];

        [weakSelf.tableView reloadData];
    }];
    [actionSheet addCancelButtonWithTitle:@"取消"];
    [actionSheet showInView:self.view];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPTimelineMessageObject *message = [self.items safeObjectAtIndex:indexPath.row];

    CGSize constrainedSize = CGSizeMake(tableView.width, 1000);

    return [PPMessageTimelineTableViewCommentCell heightForMessage:message constrainedSize:constrainedSize];
//    if(message.type == PPTimelineMessageTypeLike) {
//        return [PPMessageTimelineTableViewLikeCell heightForMessage:message constrainedSize:constrainedSize];
//    } else if(message.type == PPTimelineMessageTypeFavorite) {
//        return [PPMessageTimelineTableViewFavoriteCell heightForMessage:message constrainedSize:constrainedSize];
//    } else {
//        return [PPMessageTimelineTableViewCommentCell heightForMessage:message constrainedSize:constrainedSize];
//    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPTimelineMessageObject *message = [self.items safeObjectAtIndex:indexPath.row];

//    if(message.type == PPTimelineMessageTypeLike) {
//        PPMessageTimelineTableViewLikeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"likeCell"];
//
//        cell.delegateViewController = self;
//        cell.message = message;
//
//        return cell;
//    } else if(message.type == PPTimelineMessageTypeFavorite) {
//        PPMessageTimelineTableViewFavoriteCell *cell = [tableView dequeueReusableCellWithIdentifier:@"favoriteCell"];
//
//        cell.delegateViewController = self;
//        cell.message = message;
//
//        return cell;
//    } else {
//        PPMessageTimelineTableViewCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell"];
//
//        cell.delegateViewController = self;
//        cell.message = message;
//
//        return cell;
//    }

    PPMessageTimelineTableViewCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell"];

    cell.delegateViewController = self;
    cell.message = message;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [MobClick event:@"88"];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    PPTimelineMessageObject *message = [self.items safeObjectAtIndex:indexPath.row];
    if (message.type == PPTimelineMessageTypePickpic)
        return;

    PPAlbumObject *album = message.album;
    PPTimelinePictureObject *picture = message.picture;

    if(picture != nil) {
        PPTimelinePictureViewController *pictureViewController = [[PPTimelinePictureViewController alloc] init];
        pictureViewController.albumTitle = album.title;
        pictureViewController.ownerID = album.userID;
        pictureViewController.pictures = @[picture];
        [self.navigationController pushViewController:pictureViewController animated:YES];
    } else if(album != nil) {
        PPTimelineDetailViewController *detailViewController = [[PPTimelineDetailViewController alloc] init];
        detailViewController.album = album;
        [self.navigationController pushViewController:detailViewController animated:YES];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    [MobClick event:@"89"];
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(editingStyle == UITableViewCellEditingStyleDelete) {
        [MobClick event:@"90"];
        PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];

        [self removeItem:comment];

        [tableView reloadData];
    }

    tableView.editing = NO;
}

#pragma mark - Timeline

- (void)fetchNewItems {
    [super fetchNewItems];

    NSString *name = @"MyNotify";
    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchMyMessageListWithType:name before:nil size:kCount onlyUnread:YES callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [weakSelf didReceiveNewResult:data ? : error];
    }];
}

- (void)fetchMoreItems {
    [super fetchMoreItems];

    PPTimelineMessageObject *message = self.items.lastObject;

    NSString *name = @"MyNotify";

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchMyMessageListWithType:name before:@(message.date.timeIntervalSince1970) size:kCount onlyUnread:YES callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [self didReceiveMoreResult:error ? : data];
    }];
}

- (NSArray *)didReceiveNewResult:(id)result {
    NSArray *items = [super didReceiveNewResult:result];

    if([items count] >= kCount) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    [[PPUnreadMessageManager sharedInstance] markSummariesAsReadForType:PPUnreadMessageSummaryTypeMyNotify];

    if (_summaryType != PPUnreadMessageSummaryTypeMyNotify)
    {
        [[PPUnreadMessageManager sharedInstance] markSummariesAsReadForType:_summaryType];
    }


    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    NSArray *items = [super didReceiveMoreResult:result];

    if([items count] >= kCount) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (void)processNewItems:(NSArray *)newItems {
    NSMutableArray *items = [self valueForKey:@"items"];

    for(id item in newItems.reverseObjectEnumerator.allObjects) {
        [items insertObject:item atIndex:0];
    }

    [self cacheItems:items];
}

- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    for(NSDictionary *parameters in result) {
        PPTimelineMessageObject *message = [PPTimelineMessageObject messageForParameters:parameters];

        NSMutableArray <DGCoreTextPatternSetting *> *settings = [NSMutableArray array];
        NSString *content = nil;

        switch(message.type) {
            case PPTimelineMessageTypeFollow: {
                //                content = @"关注了你";
                content = message.brief;
                break;
            }

            case PPTimelineMessageTypeLike: {
                //                content = @"关注了你";
                content = message.brief;
                break;
            }

            case PPTimelineMessageTypeFavorite: {
                //                content = @"收藏了你";
                content = message.brief;
                break;
            }

            case PPTimelineMessageTypeComment: {
                /*
                 PPTimelineCommentObject *comment = message.comment;

                 if(comment.receiver == nil) {
                 content = comment.content;
                 } else {
                 content = [NSString stringWithFormat:@"回复 \u200C%@: %@", comment.receiver.name, comment.content];
                 }

                 content = @"aaa";

                 DGCoreTextPatternSetting *nameSetting = [[DGCoreTextPatternSetting alloc] init];
                 nameSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
                 nameSetting.defaultFont = [UIFont systemFontOfSize:15];
                 nameSetting.highlightedFont = [UIFont systemFontOfSize:15];
                 nameSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                 nameSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                 __weak typeof(self)weakSelf = self;
                 nameSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                 [weakSelf didPressedCommentReceiver:comment];
                 };
                 [settings addObject:nameSetting];
                 */
                content = message.brief;

                break;
            }


            default: content = message.brief; break;
        }

        DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
        editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
        editor.defaultFont = [UIFont systemFontOfSize:15];

        [settings enumerateObjectsUsingBlock:^(DGCoreTextPatternSetting *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            [editor preprocessWithPatternSetting:obj];
        }];

        [editor process];

        message.editor = editor;

        [items addObject:message];
    }

    return items;
}

- (void)didPressedCommentReceiver:(PPTimelineCommentObject *)comment {
    PPProfileViewController *profileViewController = [[PPProfileViewController alloc] init];
    profileViewController.userID = comment.receiver.userID;
    [self.navigationController pushViewController:profileViewController animated:YES];
}

- (UIView *)emptyPromptViewForError:(NSError *)error {
    if(error != nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = error.networkPrompt;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRGBHex:0x999999];
        [label sizeToFit];

        return label;
    } else {
        UILabel *label = [[UILabel alloc] init];
        label.text = @"没有新的消息";
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRGBHex:0x999999];
        [label sizeToFit];

        return label;
    }
}

- (NSArray *)initialItems {
    NSString *cacheFilePath = [self cacheFilePath];

    NSData *data = [NSData dataWithContentsOfFile:cacheFilePath];

    if(data != nil) {
        NSArray *items = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        for(PPTimelineMessageObject *message in items) {
            NSMutableArray <DGCoreTextPatternSetting *> *settings = [NSMutableArray array];
            NSString *content = nil;

            switch(message.type) {
                case PPTimelineMessageTypeFollow: {
                    //                content = @"关注了你";
                    content = message.brief;
                    break;
                }

                case PPTimelineMessageTypeLike: {
                    //                content = @"关注了你";
                    content = message.brief;
                    break;
                }

                case PPTimelineMessageTypeFavorite: {
                    //                content = @"收藏了你";
                    content = message.brief;
                    break;
                }

                case PPTimelineMessageTypeComment: {
                    /*
                     PPTimelineCommentObject *comment = message.comment;

                     if(comment.receiver == nil) {
                     content = comment.content;
                     } else {
                     content = [NSString stringWithFormat:@"回复 \u200C%@: %@", comment.receiver.name, comment.content];
                     }

                     content = @"aaa";

                     DGCoreTextPatternSetting *nameSetting = [[DGCoreTextPatternSetting alloc] init];
                     nameSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
                     nameSetting.defaultFont = [UIFont systemFontOfSize:15];
                     nameSetting.highlightedFont = [UIFont systemFontOfSize:15];
                     nameSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                     nameSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                     __weak typeof(self)weakSelf = self;
                     nameSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                     [weakSelf didPressedCommentReceiver:comment];
                     };
                     [settings addObject:nameSetting];
                     */
                    content = message.brief;

                    break;
                }


                default: content = message.brief; break;
            }

            DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
            editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
            editor.defaultFont = [UIFont systemFontOfSize:15];

            [settings enumerateObjectsUsingBlock:^(DGCoreTextPatternSetting *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
                [editor preprocessWithPatternSetting:obj];
            }];

            [editor process];

            message.editor = editor;
        }

        return items;
    } else {
        return nil;
    }
}

- (void)cacheItems:(NSArray *)items {
    NSString *cacheFilePath = [self cacheFilePath];

    [NSKeyedArchiver archiveRootObject:items toFile:cacheFilePath];

    [self updateNavigationBar];
}

- (NSString *)cacheFilePath {
    NSString *directory = [NSString stringWithFormat:@"%@_Message", DGCurrentAccount.userID];
    NSString *path = [[[NSFileManager defaultManager] documentDirectory] stringByAppendingPathComponent:directory];

    return path;
}

@end
